package com.geline.mybatisplus.handler.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.geline.mybatisplus.annotation.TableFieldBsm;
import com.geline.mybatisplus.handler.EntityFieldHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;

import java.lang.reflect.Field;

/**
 * 雪花标识码生成
 * 使用方式：在主表id属性上添加 @TableFieldBsm(handler = SnowflakeIdHandler.class)
 *
 * @author: mengxin
 * @date: 2023/11/13 14:37
 */
@Slf4j
public class SnowflakeIdHandler implements EntityFieldHandler<TableFieldBsm> {

    @Override
    public void before(Object entity, Field field, TableFieldBsm annotation) {
        Object fieldValue = BeanMap.create(entity).get(field.getName());
        if(fieldValue==null || StrUtil.isBlankOrUndefined(fieldValue.toString())){
            //默认使用雪花算法ID
            if(field.getType()==String.class){
                String nextId = IdUtil.getSnowflakeNextIdStr();
                BeanMap.create(entity).put(field.getName(), nextId);
            }else if(field.getType()==Long.class){
                long nextId = IdUtil.getSnowflakeNextId();
                BeanMap.create(entity).put(field.getName(), nextId);
            }else {
                String msg = String.format("un support %s[%s], just support String or Long!", field.getName(), field.getType().getSimpleName());
                throw new RuntimeException(msg);
            }
        }
    }

    @Override
    public void after(Object entity, Field field, TableFieldBsm annotation) {

    }
}
